package provider

import (
	"github.com/kingwrcy/devNews/model"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"log"
)

type MongoStorage struct {
	Storage
	Client   *mgo.Session
	Database *mgo.Database
}

const devNewsItemName = "dev_news_item"

func NewMongoStorage(addr string) MongoStorage {
	s, err := mgo.Dial(addr)
	if err != nil {
		log.Fatalf("can not connect to mongodb ")
	}
	return MongoStorage{
		Client:   s,
		Database: s.DB("devNews"),
	}
}

func (r MongoStorage) Close() {
	r.Client.Close()
}

func (r MongoStorage) Save(source string, items []model.News) bool {
	var bs []interface{}
	for _, v := range items {

		if r.Exists(v.Uuid) {
			continue
		}

		bs = append(bs, v)
		log.Printf("insert into %s ,title:%s,uuid:%s\n", source, v.Title, v.Uuid)
	}

	err := r.Database.C(devNewsItemName).Insert(bs...)
	return err == nil
}

func (r MongoStorage) Exists(uuid string) bool {
	c, _ := r.Database.C(devNewsItemName).Find(bson.M{"uuid": uuid}).Count()
	return c > 0
}

func (r MongoStorage) GetByPageSize(category string, start, offset int64) []model.News {
	var items []model.News
	_ = r.Database.C(devNewsItemName).Find(bson.M{"source": category}).Sort("-_id").Skip(int(start)).Limit(int(offset)).All(&items)
	return items
}

func (r MongoStorage) Total(category string) int {
	c, _ := r.Database.C(devNewsItemName).Find(bson.M{"source": category}).Count()
	return c
}
